<html>
<head>
    <meta http-equiv="Content-Type" content="text/html;charset=utf8">
    <title>Web sockets test</title>
 <style type="text/css">
     .container
     {
         font-family: "Courier New";
         width: 680px;
         height: 300px;
         overflow: auto;
         border: 1px solid black;
     }

     .LockOff {
         display: none; 
         visibility: hidden; 
      } 

      .LockOn { 
         display: block; 
         visibility: visible; 
         position: absolute; 
         z-index: 999; 
         top: 0px; 
         left: 0px; 
         width: 1024%; 
         height: 768%; 
         background-color: #ccc; 
         text-align: center; 
         padding-top: 20%; 
         filter: alpha(opacity=75); 
         opacity: 0.75; 
      } 
   </style> 

    <script src="jquery-min.js" type="text/javascript"></script>
    <script src="cycle.js"></script>
    <script type="text/javascript">
      var ws;
      var SocketCreated = false;
      var isUserloggedout = false;

      function lockOn(str) 
      { 
         var lock = document.getElementById('skm_LockPane'); 
         if (lock) 
            lock.className = 'LockOn'; 
         lock.innerHTML = str; 
      } 

      function lockOff()
      {
         var lock = document.getElementById('skm_LockPane'); 
         lock.className = 'LockOff'; 
      }

      function ToggleConnectionClicked() {
            if (SocketCreated && (ws.readyState == 0 || ws.readyState == 1)) {
                lockOn("离开IM服务器...");  
                SocketCreated = false;
                isUserloggedout = true;
                ws.close();
            } else {
                lockOn("进入即时通讯...");  
                Log("准备连接到IM服务器 ...");
                try {
                    if ("WebSocket" in window) {
                    	ws = new WebSocket("ws://" + document.getElementById("Connection").value);
                    }
                    else if("MozWebSocket" in window) {
                    	ws = new MozWebSocket("ws://" + document.getElementById("Connection").value);
                    }
                    
                    SocketCreated = true;
                    isUserloggedout = false;
                } catch (ex) {
                    Log(ex, "ERROR");
                    return;
                }
                document.getElementById("ToggleConnection").innerHTML = "断开";
                ws.onopen = WSonOpen;
                ws.onmessage = WSonMessage;
                ws.onclose = WSonClose;
                ws.onerror = WSonError;
            }
        };


        function WSonOpen() {
            lockOff();
            Log("连接已经建立。", "OK");
            $("#SendDataContainer").show();
            var sendStr='{"stype":"join","message":"' + document.getElementById("txtName").value+'"}';
            //ws.send("{\"stype\":\"join\",\"message\":\"你好\"}");
   			   ws.send(sendStr);
            ws.send('{"stype":"getusers"}');
        };

        function WSonMessage(event) {
            var obj = JSON.parse(event.data); //由JSON字符串转换为JSON对象
            if(obj.stype=="Hi~")
            {
                //Log("你在服务器的信息:");
                Log("fd:"+obj.fd+" uuid:"+obj.uuid);
                Log(obj.message);
             }
            else if(obj.stype=="message")
            {
                Log(obj.form+" 说："+obj.message);
            }
            else if(obj.stype=="onlineClients")
            {
                
                obj.arrayUser.filter((p) => {
                        Log("fd:"+p.fd+" nickname:"+p.nickname+" uuid:"+p.uuid);   
                        addClientItem(-1,p.nickname);                     
                });
                
            }
            else
            Log(event.data);            
        };

        function WSonClose() {
            lockOff();
            if (isUserloggedout)
                Log("【"+document.getElementById("txtName").value+"】离开了聊天室！");
            document.getElementById("ToggleConnection").innerHTML = "连接";
            $("#SendDataContainer").hide();
        };

        function WSonError() {
            lockOff();
            Log("远程连接中断。", "ERROR");
        };
        /*****************************
        *添加客户
        ******************************/
        function addClientItem(n,txt){
            var div=document.getElementById('lineClients'); 
            var ul=div.childNodes.item(0); 
            var lis=ul.childNodes; 
            var li=document.createElement("li");
            li.innerHTML=txt;
            for(var i=0;i<lis.length;i++)
            {
                if(n==-1)
                {
                    ul.appendChild(li);
                }
                else if(i==n-1)
                {
                    ul.insertBefore(li,lis[i]);
                }
             }          
           
        };

        function SendDataClicked() {
            if (document.getElementById("DataToSend").value.trim() != "") {
                ws.send(document.getElementById("txtName").value + "说 :\"" + document.getElementById("DataToSend").value + "\"");
                document.getElementById("DataToSend").value = "";
            }
        };


        function Log(Text, MessageType) {
            if (MessageType == "OK") Text = "<span style='color: green;'>" + Text + "</span>";
            if (MessageType == "ERROR") Text = "<span style='color: red;'>" + Text + "</span>";
            document.getElementById("LogContainer").innerHTML = document.getElementById("LogContainer").innerHTML + Text + "<br />";
            var LogContainer = document.getElementById("LogContainer");
            LogContainer.scrollTop = LogContainer.scrollHeight;
        };


        $(document).ready(function () {
            $("#SendDataContainer").hide();
            var WebSocketsExist = true;
            try {
                var dummy = new WebSocket("ws://localhost:8989/test");
            } catch (ex) {
                try
                {
                	webSocket = new MozWebSocket("ws://localhost:8989/test");
                }
                catch(ex)
                {
                	WebSocketsExist = false;
                }
            }

            if (WebSocketsExist) {
                Log("您的浏览器支持WebSocket. 您可以尝试连接到聊天服务器!", "OK");
                document.getElementById("Connection").value = "127.0.0.1:9753";
            } else {
                Log("您的浏览器不支持WebSocket。请选择其他的浏览器再尝试连接服务器。", "ERROR");
                document.getElementById("ToggleConnection").disabled = true;
            }    
            
            $("#DataToSend").keypress(function(evt)
            {
            		if (evt.keyCode == 13)
            		{
            				$("#SendData").click();
            				evt.preventDefault();
            		}
            })        
        });

    </script>
</head>
<body>
    <div id="skm_LockPane" class="LockOff"></div>
    <form id="form1" runat="server">
        <h1>Web Socket IM</h1>
        <br />
        <div>
            按下连接按钮，会通过WebSocket发起一个到IM服务器浏览器的连接。
        </div>
        服务器地址: <input type="text" id="Connection" /> 用户名： <input type="text" id="txtName" value="黄晓安"/>
        <button id='ToggleConnection' type="button" onclick='ToggleConnectionClicked();'>连接</button>
        <br />
        <br />
        <div id='LogContainer' class='container'></div>
        <br />        
        <div id='SendDataContainer'>
        <div id='lineClients'><ul><li></li></ul></div>
        <input type="text" id="DataToSend" size="88" />
        <button id='SendData' type="button" onclick='SendDataClicked();'>发送</button>
        </div>
        <br />
    </form>
</body>
</html>

